define(['app', 'datetime', 'pagination', 'editor', 'exporting', 'filesaver', 'fileupload','js/service/agupload','floatlayer'], function(app) {
    'use strict';
    app.controller('Contract', function($scope, dataFactoryCRM, $q, Upload, $http,AgUpload) {
        $scope.batchSignCheck = [];
        //默认数据
        $scope.contractList = [];
        $scope.contractId = '';
        $scope.payrecordId = '';
        $scope.record;
        $scope.index_key = '5';
        $scope.sweepContract = '';
        $scope.check_status = '';
        $scope.mount = 0;
        $scope.sweep_contract = '' ;
        $scope.value1 = false;
        $scope.delivery_status = "待寄出";
        //默认分页
        $scope.ContractPage = { pageAll: 1, pageNow: 1, pageSize: 20, k: 3,pageName: 'ContractPage' };
        //默认检索条件
        $scope.search = { customer: '', sales: '', first_time: '', second_time: '', product: '',export:0 };
        //默认select数据
        $scope.details = [{ k: '0', v: '纸质合同' }, { k: '1', v: '合同发票' }, { k: '2', v: '终止协议' }, { k: '3', v: '其他' }];
        $scope.sign_status = [{ k: '0', v: '未处理' }, { k: '10', v: '签订完成' }];
        $scope.deliveryStatus = [{ k: '0', v: '未处理' }, { k: '1', v: '邮寄中' }, { k: '2', v: '邮寄完成' }, { k: '3', v: '被退回' }, { k: '4', v: '挂起' }];
        //合同类型
        $scope.contract_type = [{ k: '0', v: "未知" }, { k: '1', v: "纸质合同" }, { k: '2', v: "电子合同" }];
        //合同状态
        $scope.contract_status = [{ k: '-1', v: '已取消' }, { k: '0', v: '待审核' }, { k: '1', v: '进行中' }, { k: '2', v: '升级作废' }, { k: '3', v: '已完成' }, { k: '4', v: '签订中' }];
        //是否违规
        $scope.contract_weigui = [{ k: '0', v: "未知" }, { k: '11', v: "违规未导出" }, { k: '12', v: "违规已导出" }, { k: '21', v: "不违规" }];
        //公用数据
        $scope.busy = dataFactoryCRM.getDataByAPI('Contract/productData').then(function(data) {
            $scope.productList = data.product;
            $scope.today = data.today;
           if($("#Contract-model").length==0)  
            $scope.contractDetails = 1; 
        });

        //条件搜索
        $scope.search_list = function() {
            var listParam = $scope.search;
            listParam['psize'] = $scope.ContractPage.pageSize;
            listParam['p'] = 1;
            listParam['state'] = $scope.searchKey;
            var _url = 'Contract/index?state=' + $scope.searchKey + '&' + $.param(listParam);
            $scope.getData(_url);
        };
        //默认首页
        $scope.ContractList = function(key, val) {

            if (key != undefined && key != $scope.searchKey) {
                $scope.search.customer = '';
                $scope.search.sales = '';
                $scope.search.first_time = '';
                $scope.search.second_time = '';
                $scope.search.product = '';
                $scope.searchKey = key;
                $scope.ContractPage.pageNow = 1;
            } else {
                $scope.ContractPage.pageNow = $scope.ContractPage.pageNow;
                $scope.searchKey = $scope.searchKey;
            }
            if ($scope.searchKey == '6') $scope.cont_but = false;
            else $scope.cont_but = true;

            var _url = 'Contract/index?state=' + $scope.searchKey + '&sales=' + $scope.search.sales +'&product'+$scope.search.product+'&customer='+$scope.search.customer+'&first_time='+$scope.search.first_time+'&second_time='+$scope.search.second_time+ '&psize=' + $scope.ContractPage.pageSize + '&p=' + $scope.ContractPage.pageNow;
            $scope.getData(_url);
        }
        $scope.getData = function(_url) {
            dataFactoryCRM.getDataByAPI(_url)
                .then(function(data) {
                    if (data.rcode) {
                        $scope.ContractPage.dataCount = data.count;
                        $scope.contractList = data.contract;
                        $scope.ContractPage.pageSize = data.psize;
                        $scope.ContractPage.pageAll = data.pall;
                        $scope.ContractPage.pageNow = data.p;
                    } else {
                        $scope.ContractPage.pageAll = 0;
                    }
                })
        }
        //特殊处理semantic dropdown的反向绑定缺陷
        $scope.$watch('search.product', function(newValue, oldValue) {
            setTimeout(function() {
                angular.element("select[ng-model='search.product']").dropdown('set selected', newValue);
            });
        }, true);

        //初始化页面显示数据（如果是新弹出独立窗口则从父窗口获取）
        window.loadClientCacheToScope($scope, function() {
            $scope.ContractList($scope.index_key);
        });
        $scope.sweepSubmit = function(){
            if($scope.sweepContract!=""){
                $scope.sweepDetection();
                 setTimeout(function() {
                    var checkExist = $("#isExist").val();
                    if($('#frm-sweep').form('is valid') && checkExist ==-1){
                        $scope.sweepShow($scope.sweepContract);
                    }else{     
                        if(checkExist == 1){
                            $("#checkSweep").select();  
                        }
                        return false;
                    }
                 }, 100)
             }
        }
         //合同扫码
        $scope.sweep        = function(){
           $('#frm-sweep').form('clear');
           $scope.sweepContract='';
           $scope.sweepResults = true;
           $('.ui.sweep').modal({
                observeChanges: true,
                onApprove: function() {
                    var checkExist = $("#isExist").val();
                    if($('#frm-sweep').form('is valid') && checkExist ==-1){
                        $scope.sweepSubmit($scope.sweepContract);
                      }else{ 
                        return false;
                    }
                }
            }).modal('show');           
        }
        //扫码数据检测
        $scope.sweepShow   = function(sweepId){
            dataFactoryCRM.getDataByAPI("Contract/sweepContract?order_num="+sweepId)
                .then(function(data) {
                   if(data.rcode == 1){
                        $scope.sweep_contract = data.sweep;
                        $scope.mail_contract($scope.sweep_contract);
                        $scope.sweepResults = true;
                   }else{
                        $scope.sweepResults = false;
                   }
                })
        }
        //扫码监测
        $scope.sweepDetection = function(){
            dataFactoryCRM.getDataByAPI("Contract/sweepDetection?order_num="+$scope.sweepContract)
                .then(function(data) {
                   if(data.rcode == 1){
                        $("#isExist").val(-1);  
                   }else{
                        $("#isExist").val(1);
                   }
            })
        }
        $scope.$watch('sweepContract', function(ov, nv) {
           $scope.sweepDetection();
        });

        //编辑合同
        $scope.editor_show = function(key) {
            //时间插件验证
            $scope.text_error = true;
            $scope.text_wrong = true;
            //编辑合同加载
            $('.ui.editor').modal({
                onApprove: function() {
                    var startTime = $("#start_time").val();
                    var endTime = $("#end_time").val();
                    var timestamp1 = new Date(startTime), timestamp2 = new Date(endTime); 
                    var date = timestamp2.getTime()-timestamp1.getTime();

                    if ($('#frm-editor').form('is valid') && startTime != '' && endTime != '' && date > 0) {
                        $scope.contract_editor($('#frm-editor').serialize());
                    } else {
                        
                        //时间插件检验
                        if (startTime != '') {
                            $scope.text_error = true;
                            $("#stime_check").removeClass("error");
                        } else {
                            $scope.text_error = false;
                            $scope.messageText = '开始时间不能为空';
                            $scope.isError = true;
                            return false;
                        }
                        if (endTime != '') {
                            $scope.text_wrong = true;
                        } else {
                            $scope.text_wrong = false;
                            $scope.messageTexts = '结束时间不能为空';
                            $scope.isWrong = true;
                            return false;
                        }
                        if (date < 0 || date == 0) {
                            $scope.text_error = false;
                            $scope.messageText = '开始时间不能大于、等于结束时间!!!';
                            $scope.isError = true;
                            return false;
                        }
                        return false;
                    }
                }
            }).modal('show');
            dataFactoryCRM.getDataByAPI("Contract/editor?contract_id="+ key)
                .then(function(data) {
                    $scope.editor = data.editor;
                    //下拉默认值
                    $('#product_').dropdown('set selected', $scope.editor.product_id);
                    $('#statu_').dropdown('set selected', $scope.editor.state);
                    $('#sign_').dropdown('set selected', $scope.editor.sign_status);
                    if ($scope.contractId == '') $("#cId").val($scope.editor.contract_id);
                    $('#frm-editor input[name="check_customer"]').val(0);
                    $('#frm-editor input[name="check_customer_phone"]').val(0);
                    $scope.object=[$scope.editor.second_party_name,$scope.editor.second_party_phone];
            })

            // 客户信息监测
            $scope.$watch('editor.second_party_name', function(newValue, oldvalue){
                if(newValue!=oldvalue && oldvalue!=undefined){
                     var url = "Contract/checkCustomer?customer_id="+$scope.editor.customer_id+'&customer_name='+$scope.editor.second_party_name+'&customer_phone='+$scope.editor.second_party_phone;
                     dataFactoryCRM.getDataByAPI(url)
                        .then(function(data) {
                        if(data.exist == false){
                            $scope.check_customer = 0;
                            $("#frm-editor .check_field").removeClass("error");
                             $('.ui.basic.red.pointing.prompt.label.transition.visible').remove();
                        }else{
                            $scope.check_customer = 1;
                        }
                        $('#frm-editor input[name="check_customer"]').val($scope.check_customer);
                    })
                }
            });
          $scope.$watch('editor.second_party_phone', function(news, old){
                if(news!=old && old!=undefined){
                     var url = "Contract/checkCustomer?customer_id="+$scope.editor.customer_id+'&customer_name='+$scope.editor.second_party_name+'&customer_phone='+$scope.editor.second_party_phone;
                     dataFactoryCRM.getDataByAPI(url)
                        .then(function(data) {
                        if(data.exist == false){
                            $scope.check_customer = 0;
                            $("#frm-editor .check_field").removeClass("error");
                             $('.ui.basic.red.pointing.prompt.label.transition.visible').remove();
                        }else{
                            $scope.check_customer = 1;
                        }
                        $('#frm-editor input[name="check_customer"]').val($scope.check_customer);
                    })
                }
            });
        }
        //合同编辑
        $scope.contract_editor = function(_d) {
            dataFactoryCRM.postDataByAPI("Contract/editor", _d)
                .then(function(data) {
                    if (data.rcode == 1) {
                        $('.ui.modal5').modal('show');
                        $scope.Msg = "编辑成功";
                    } else {
                        $('.ui.modal2').modal('show');
                        $scope.Msg = "编辑失败";
                    }

                    setTimeout(function() {
                        $('.time').modal('hide')
                    }, 3000)
                    $scope.ContractList($scope.searchKey);
                })   
        }
        
        //打印合同界面加载
        $scope.print_show = function() {
            $scope.view = this.vlist;
            $(".ui.print").modal('show');
        }

        //打印合同
        $scope.print_contract = function() {
            window.frames["print_frame"].document.body.innerHTML = $("#printBox").html();
            window.frames["print_frame"].window.focus();
            window.frames["print_frame"].window.print();
        }
        //合同合并
        $scope.merge_show = function() {
            $("#frm-merge").form('reset');
            $scope.merge = this.vlist;
            $scope.mount = parseInt($scope.merge.mount);

            $('.ui.merge').modal({
                onApprove: function() {
                    $scope.mount = $scope.mount;
                    if ($('#frm-merge').form('is valid')) {

                        var checkbox = [];
                        $('input[name="checkbox"]:checked').each(function() {
                            checkbox.push($(this).val());
                        });

                        $scope.stime = $("#stime").val();
                        $scope.etime = $("#etime").val();
                        $scope.product = $("#productId").val();

                        dataFactoryCRM.postDataByAPI('Contract/merge_editor', { checkbox: checkbox, main: $scope.merge, stime: $scope.stime, etime: $scope.etime, mount: $scope.mount, product: $scope.product })
                            .then(function(data) {
                                if (data.msg) {
                                    $(".ui.modal2").modal('show');
                                    $scope.Msg = "合并失败";
                                } else {
                                    $(".ui.modal5").modal('show');
                                    $scope.Msg = "合并成功";
                                }

                                setTimeout(function() {
                                    $('.time').modal('hide')
                                }, 3000);
                                $scope.ContractList($scope.searchKey);
                            })
                    } else {
                        return false;
                    }
                }
            }).modal('show');
            dataFactoryCRM.getDataByAPI('Contract/merge_show?customer_id=' + $scope.merge.customer_id)
                .then(function(data) {
                    if (data.rcode) {
                        $scope.merge_record = data.merge_contract;
                        for (var i = 0; i < $scope.merge_record.length; i++) {
                            if ($scope.merge.contract_id == $scope.merge_record[i].contract_id) {
                                $scope.mergeId = $scope.merge_record[i].contract_id;
                            }
                        }
                    }
                })
        };

        //可能存在的合同加载
        $scope.may_exist = function() {
            dataFactoryCRM.getDataByAPI('Contract/merge_show?customer=' + $scope.may + '&customer_id=' + $scope.merge.customer_id)
                .then(function(data) {
                    $scope.merge_record = data.merge_contract;
                })
        }
        //邮寄信息加载
        $scope.view_contract = function() {
            $scope.view = this.vlist;
            $('.ui.view').modal({
                observeChanges: true,
                onApprove: function() {

                }
            }).modal('show');
        }
        //合同邮寄
        $scope.mail_contract = function(param) {
            $('#signDefault>.text').text('合同签订状态');
            $('#signDefault input[name="sign_status"]').val('');     
            if(param){
               $scope.sweepParam =1;
               $scope.mail = param;
               $scope.sweepMail = false;
               $scope.ordinaryMail = true;
               $scope.herfParam = 20;
               $("#confirmParam").val('1');//隐藏域赋值
            }else{
                $scope.sweepMail = true;
                $scope.ordinaryMail = false;
                $scope.sweepParam =2;
                $scope.mail = this.vlist;
                $scope.herfParam = 10;
                $("#confirmParam").val('2');//隐藏域赋值
            }
             
            $scope.default_date = $scope.today;
            $scope.mail_tel = $scope.mail.phone;
            //隐藏域赋值
            $("#manager").val($scope.mail.manager_id);
            $("#contract").val($scope.mail.contract_id);
            $("#customerId").val($scope.mail.customer_id);
            $("#sales_person").val($scope.mail.user_id);
            $("#sectorId").val($scope.mail.sector_id);
            $("#companyId").val($scope.mail.company_id);
            
            $scope.check_times = true;
            $('.ui.mail').modal({
                observeChanges:true,
                onApprove: function() {
                    $("#delivery").val($scope.record.delivery_id);
                    if ($('#frm-mail').form('is valid') && $("#send_time").val() != '') {
                        var mail = $('#frm-mail').serialize();
                        dataFactoryCRM.postDataByAPI('Delivery/deliveryAdd', mail)
                            .then(function(data) {
                                if($scope.sweepParam == 1){
                                    $(".ui.modal5").modal('show');
                                    setTimeout(function() {
                                        $('.time').modal('hide');
                                        $scope.sweep();
                                    }, 1000);
                                }else{
                                    if (data.rcode ) {  
                                        $('.ui.mail_record').modal('show');
                                         $scope.fineMsg = data.msg;
                                    } else {
                                        $(".ui.modal2").modal('show');
                                         setTimeout(function() {
                                          $('.time').modal('hide')
                                        },3000);
                                    }
                                    $(".ui.mail_record").modal('show');
                                }
                                  
                                $scope.ContractList($scope.searchKey);
                            })
                    } else {
                        if ($("#send_time").val() != '') {
                            $scope.check_times = true;
                        } else {
                            $scope.check_times = false;
                            $scope.messageText = '开始时间不能为空';
                            $scope.isError = true;
                        }
                        return false;
                    }
                }
            }).modal('show');
            var url = 'Contract/mail?contract_id=' + $scope.mail.contract_id;
            dataFactoryCRM.getDataByAPI(url)
                .then(function(data) {
                    $('#frm-mail input[name="address"]').val('33');
                    $scope.mailMessage = false;
                    $scope.remarkMessage= true;
                    if (data.rcode) {
                        $scope.mail.child = data.delivery;
                        $scope.record = data.record;
                        if($scope.record.address == "")
                            $('#signDefault input[name="address"]').val('');     
                        $scope.telephone = $scope.record.phone;
                        $("#mailStatus").val($scope.record.status);
                        $("#mailId").val($scope.record.delivery_id);
                        if($scope.record.status == 40 || $scope.record.status == 50 || $scope.record==null ){
                            $scope.mailTitle = "合同邮寄添加";
                        }else{

                            if($scope.record.status != 10){
                                $scope.remarkMessage = false;
                                $scope.mailMessage   = true;
                            }
                            if($scope.record.status == 20 || $scope.record.status == 30)
                                $scope.mailTitle = "合同邮寄查询";
                            else
                                $scope.mailTitle = "合同邮寄确认";
                        }
                        $scope.mail_empty = false;
                    } else {
                        if(param)  $("#mailStatus").val(10);
                        $scope.mailTitle = "合同邮寄添加";
                        $scope.mail_empty = true;
                        $scope.record = $scope.mail;
                        $scope.mail.tel = $scope.mail.phone;
                        $scope.record.recipients = $scope.record.customer_name;
                    }
                })
        }
        //取消提醒
        $scope.cancel_remind = function(key) {
            $scope.remind_id = key;
            $('.ui.delete').modal('show');
        }
        //取消合同
        $scope.cancel = function(cId) {
            dataFactoryCRM.getDataByAPI("Contract/cancel?contract_id=" + cId)
                .then(function(data) {
                    if (data.rcode == 1) {
                        $(".ui.modal5").modal('show');
                        $scope.Msg = "取消成功";
                    } else {
                        $(".ui.modal2").modal('show');
                        $scope.Msg = "取消失败";
                    }

                    setTimeout(function() {
                        $('.time').modal('hide')
                    }, 3000);
                    $scope.ContractList($scope.searchKey);
                })
        }
        //批量编辑
        $scope.batch_show = function() {
            $scope.style = { "color": "#a9a9a9" }
            $("#frm-batch").form('reset');
            $("#check_all").removeAttr("checked");
            var listParam = $scope.search;
            $('.ui.batch').modal({
                observeChanges: true,
                onApprove: function() {
                    var checkbox = [];
                    $('input[name="checkbox_mail"]:checked').each(function() {
                        checkbox.push($(this).val());
                    });

                    var content = [];
                    for (var i = 0; i < $scope.batchList.length; i++) {
                        for (var s = 0; s < checkbox.length; s++) {
                            if (checkbox[s] == $scope.batchList[i].contract_id) {
                                content.push($scope.batchList[i]);
                            }
                        }
                    }
                    
                    dataFactoryCRM.postDataByAPI('Contract/batch_editor', { batch: content })
                        .then(function(data) {

                            if (data.failure) {
                                $('.ui.error_shw').modal('show');
                                $scope.failure = data.failure;
                            } else {
                                $('.ui.mail_record').modal('show');
                                $scope.fineMsg = "全部信息编辑成功!!!";
                            }
                            setTimeout(function() {
                                $('.time').modal('hide')
                            }, 3000)
                            $scope.ContractList($scope.searchKey);
                        })
                }
            }).modal('show');
            var _url = 'Delivery/batch';
            dataFactoryCRM.getDataByAPI(_url)
                .then(function(data) {
                    $scope.batch_empty = false;
                    if (data.contract && data.contract.length > 0) {
                        $scope.batch_empty = true;
                        $scope.batchList = data.contract;
                    } else {
                        $scope.batchList = '';
                        $scope.batchPage.pageAll = 0;
                    }
                })
        }

        //合同批量导出
        $scope.export_contract = function() {
            var listParam = $scope.search;
            listParam.export = 1;
            dataFactoryCRM.getDataByAPI('Contract/index?state=' + $scope.searchKey + $.param( listParam ) ,true).then( function(response ) {
                $scope.search.export = 0;
                if( response && response.rcode ){
                    AgUpload.downExcel(response.data.view_path, "合同数据记录表");
                }
                else{
                    $('<div class="ui small modal modal2" style="text-align: center;"><div class="header">提示</div><div class="content"><i class="huge red warning outline icon"></i>' +
                        '<p style="padding-top: 15px;">'+response.msg+'</p>' +'</div></div>'
                    ).modal('show');
                }
            });
        }

        //违规批量导出
        $scope.export_violations = function() {;
            dataFactoryCRM.getDataByAPIS('Contract/export_violations').then(function(response) {
                var blob = new Blob([response], {
                    type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
                });
                saveAs(blob, '违规数据记录表' + '.xls');
            });
        }

        // checkbox / radio 合同默认报价计算
        $scope.radio_show = function($event, contractId, key, order_num) {
            $("#checkbox" + contractId).prop('checked', true);
            var contractidArr = $("input:checkbox[name='checkbox']:checked").map(function(index, elem) {
                return $(elem).val();
            }).get().join(',');
            $scope.list = contractidArr.split(',');
            var money = 0;
            for (var i = 0; i < $scope.list.length; i++) {
                for (var s = 0; s < $scope.merge_record.length; s++) {
                    if ($scope.list[i] == $scope.merge_record[s].contract_id) {
                        money += parseInt($scope.merge_record[s].mount);
                    }
                }
            }
            $scope.mount = parseInt(money);
        }
        //批量邮寄checkbox检测
        $scope.check_checkbox = function(Id) {
            for (var i = 0; i < $scope.batchList.length; i++) {
                $("#send_time" + $scope.batchList[i].contract_id).prop("disabled", "disabled");
                $("#recipients" + $scope.batchList[i].contract_id).prop("disabled", "disabled");
                $("#address" + $scope.batchList[i].contract_id).prop("disabled", "disabled");
                $("#remark" + $scope.batchList[i].contract_id).prop("disabled", "disabled");
                $("#phone" + $scope.batchList[i].contract_id).prop("disabled", "disabled");
                $("#send_time" + $scope.batchList[i].contract_id).css("color", "#a9a9a9");
                $("#recipients" + $scope.batchList[i].contract_id).css("color", "#a9a9a9");
                $("#address" + $scope.batchList[i].contract_id).css("color", "#a9a9a9");
                $("#remark" + $scope.batchList[i].contract_id).css("color", "#a9a9a9");
                $("#phone" + $scope.batchList[i].contract_id).css("color", "#a9a9a9");
            }
            var checkbox = [];
            $('input[name="checkbox_mail"]:checked').each(function() {
                checkbox.push($(this).val());
            });
            var content = [];
            for (var s = 0; s < checkbox.length; s++) {
                $("#send_time" + checkbox[s]).removeAttr("disabled");
                $("#recipients" + checkbox[s]).removeAttr("disabled");
                $("#address" + checkbox[s]).removeAttr("disabled");
                $("#remark" + checkbox[s]).removeAttr("disabled");
                $("#phone" + checkbox[s]).removeAttr("disabled");
                $("#send_time" + checkbox[s]).css("color", "black");
                $("#recipients" + checkbox[s]).css("color", "black");
                $("#address" + checkbox[s]).css("color", "black");
                $("#remark" + checkbox[s]).css("color", "black");
                $("#phone" + checkbox[s]).css("color", "black");
            }
        }
        //合同管理按钮
        $scope.operation = function(key) {
            //分页20条内容，后五条dropdown向上显示
            if(key%20 > 14){
                $('#menu' + key).dropdown({direction: 'upward'});
            }else{
                $('#menu' + key).dropdown();
            }
        }

        $scope.checkTime = function() {
            if ($("#send_time").val() != '') {
                $scope.check_times = true;
            } else {
                $scope.check_times = false;
                $scope.messagesTextse = '邮寄时间不能为空!!!';
                $scope.isSend_time = true;
            }
        }
        //时间插件检验
        $scope.check_time = function() {
            $scope.isError = false;
            $scope.isWarning = false;

            var startTime = $("#start_time").val();
            var endTime = $("#end_time").val();
            var timestamp1 = new Date(startTime), timestamp2 = new Date(endTime); 
            var date = timestamp2.getTime()-timestamp1.getTime();

            if (startTime != '') {
                $scope.text_error = true;
            } else {
                $scope.text_error = false;
                $scope.messageText = '开始时间不能为空';
                $scope.isError = true;
            }
            if (endTime != '') {
                $scope.text_wrong = true;
            } else {
                $scope.text_wrong = false;
                $scope.messageTexts = '结束时间不能为空';
                $scope.isWrong = true;
            }
             if (date < 0 || date ==0 ) {
                $scope.text_error = false;
                $scope.messageText = '开始时间不能大于、等于结束时间!!!';
                $scope.isError = true;
            }else{
                $scope.text_error = true;
            }
        }

        $scope.api_error = function ( msg ) {
            $('.modal.modal2').remove();
            $('<div class="ui small modal modal2" style="text-align: center;"><div class="header">提示</div><div class="content"><i class="huge red warning outline icon"></i>' +
                '<p style="padding-top: 15px;">'+msg+'</p>' +'</div></div>'
            ).modal('show');
        };

        $scope.api_success = function( msg ){
            $('.modal.modal1').remove();
            $('<div class="ui small modal modal1" style="text-align: center;"><div class="header">提示</div><div class="content"><i class="huge green check circle outline icon"></i>' +
                    '<p style="padding-top: 15px;">'+msg+'</p>' +'</div></div>'
                ).modal('show');
        };

        //电子合同签订
        $scope.econtract = function( contract_id ) {
            function _sendContract(){
                dataFactoryCRM.postDataByAPI('contract/econtract',  $scope.econtractData).then(
                    function(d){
                        if (d&&d.rcode) {
                            $('.ui.econtract.modal').modal('hide');
                            $scope.api_success("电子合同录入成功");
                            $scope.ContractList($scope.searchKey);
                        }
                        else
                           $scope.api_error( d.msg );
                    },
                    function(err){
                         $scope.api_error("电子合同推送接口访问失败");
                    });
            }

            dataFactoryCRM.getDataByAPI('contract/econtract?contract_id='+contract_id).then(
                function(d){
                if (d&&d.rcode){
                    $scope.econtractData = d.data;
                    $('.ui.econtract.modal .form').removeClass("loading");
                    $('.ui.econtract.modal')
                    .modal({
                        observeChanges: true,
                        onApprove:function(){
                            if ($('.ui.econtract.modal .form').hasClass("loading"))
                                return false;
                            _sendContract();
                            $('.ui.econtract.modal .form').addClass("loading");
                            return false;
                        }
                    })
                    .modal('refresh')
                    .modal('show');
                }
                else {
                     $scope.api_error( d.msg );
                    alert(d.msg);
                }
            },
            function(err){
                 $scope.api_error("无权限");
            });
        };

        //批量电子合同
        $scope.batchEcontract = function(){
            var arrContract = [];
            $scope.batchSignCheck = [];
            for(var i=0;i<$scope.contractList.length; i++ ) {
                arrContract.push( $scope.contractList[i].contract_id );
            }
            var data = {api:'load', data:arrContract};
            function _updateListMsg(cid, msg){
                for(var ic=0;ic<$scope.batchContractData.length; ic++) {
                    if ($scope.batchContractData[ic].contract_id == cid){
                        $scope.batchContractData[ic].msg = msg;
                        $scope.batchContractData[ic].code = 1; 
                        var key = '.ui.batch_econtract input[value="'+cid+'"]';
                        if (msg != '提交成功'){
                            $(key).parent().parent().addClass('negative').addClass('message');
                        }
                        else 
                            $(key).parent().parent().addClass('positive').addClass('message');
                    }
                }
            }

            function _sendContract( _ids ){
                var tc = 0;
                var key = '';
                $scope.sign_contract_id = 0;
                for (var ic=0;ic<_ids.length;ic++){
                    $scope.sign_contract_id = _ids[ic];
                    key = '.ui.batch_econtract input[value="'+_ids[ic]+'"]';
                    $(key).attr('checked', false);
                    $(key).attr('disabled', true);
                    dataFactoryCRM.postDataByAPI('contract/econtract', {contract_id:_ids[ic]}).then(
                        function(d){
                            if (d&&d.rcode) {
                                tc++;
                                $scope.ContractList($scope.searchKey);//只要更新合同成功就刷新列表页
                                _updateListMsg(d.contract_id , '提交成功');
                            }
                            else
                                _updateListMsg(d.contract_id , d.msg);
                    });
                }
                $scope.sign_contract_id = 0;
                if (tc==$scope.batchContractData.length) {
                    $('.ui.batch_econtract').modal('hide');
                    $scope.api_success("电子合同批量数据录入成功!"); 
                    return true;  
                }
            }

            $scope.batch_econtracht_all = 0;
            dataFactoryCRM.postDataByAPI('contract/batchEcontract', data).then(
                function(d){
                if (d&&d.rcode){
                    $scope.batchContractData = d.data;
                    for(var i=0;i<$scope.batchContractData.length; i++ ) {
                        $scope.batchContractData[i].code = 0;
                        $scope.batchSignCheck[i] = false;
                    }
                    $('.ui.batch_econtract.large.modal .form').removeClass("loading");
                    $('.ui.batch_econtract.large.modal')
                    .modal({
                        observeChanges: true,
                        onApprove:function(){
                            if ($('.ui.batch_econtract .form').hasClass("loading"))
                                return false;
                            arrContract = [];
                            for (i=0;i<$scope.batchSignCheck.length; i++ ) {
                                if ($scope.batchSignCheck[i] && !$scope.batchContractData[i].code )
                                    arrContract.push( $scope.batchContractData[i].contract_id );
                            }

                            if ($scope.sign_contract_id) {// 防止合同提交中，重复提交
                                return false;
                            }
                            if (arrContract.length > 0) {
                                _sendContract( arrContract );
                                return false;
                            }
                            else{
                                $scope.api_error("选中提交合同为空");
                                return true;
                            } 
                        }
                    })
                    .modal('refresh')
                    .modal('show');
                }
                else {
                     $scope.api_error( d.msg );
                    alert(d.msg);
                }
            },
            function(err){
                 $scope.api_error("获取合同签订信息失败");
            });
        };

        //监听批量电子合同 checkbox
        $scope.$watch('batch_econtracht_all', function(newValue, oldvalue){
            var v = newValue===true ? true:false;
            for(var i=0;i<$scope.batchSignCheck.length; i++) {
                if (!$('.ui.batch_econtract input:eq('+i+')').parent().parent().hasClass('disabled'))
                    $scope.batchSignCheck[i] = v;
            }
        });
    });
});
